package com.coder520.mamabike.b.presenter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.baidu.mapapi.model.LatLng;
import com.coder520.mamabike.b.entity.BikeLockTo;
import com.coder520.mamabike.b.entity.Point;
import com.coder520.mamabike.b.ui.activity.PositionChooseActivity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.coder520.mamabike.b.R;
import com.coder520.mamabike.b.internet.DataListener;
import com.coder520.mamabike.b.manager.BikeManager;
import com.coder520.mamabike.b.ui.UiControlInterface;
import com.coder520.mamabike.b.ui.activity.MainActivity;
import com.coder520.mamabike.b.utils.CommonUtils;
import com.coder520.mamabike.b.utils.DeviceInfoUtils;
import com.coder520.mamabike.b.utils.UIUtils;

import static android.R.attr.width;

/**
 * Created by zhongyanli on 2017/10/13.
 */

public class MainPresenter extends BasePresenter {
    private static final int REQUEST_CODE_POSITION = 10;
    private static final int MSG_LOAD_BIKE_STATE = 1;
    private static final int MSG_DISMISS_PREGRESS_DIALOG = 2;
    private static final int MSG_LOAD_BIKE_DELAY = 10 * 1000;
    private BikeManager bikeManager = BikeManager.getInstance();
    private MainActivity mActivity;

    public MainPresenter(UiControlInterface uiControlInterface) {
        super(uiControlInterface);
        mActivity = (MainActivity) uiControlInterface;
    }

    public void setCurrentBikeNumber(String number) {
        bikeManager.setCurrentBikeNumber(number);
        mHandler.removeMessages(MSG_LOAD_BIKE_STATE);
        mActivity.setCurrentBikeNumber(number);
        mActivity.setShowQrButtonEnabled(true);
        createLoadBikeMessage(bikeManager.getCurrentBikeNumber()).sendToTarget();
    }

    public void onLockClick() {
        Intent intent = new Intent(mContext, PositionChooseActivity.class);
        mActivity.startActivityForResult(intent, REQUEST_CODE_POSITION);
    }

    @Override
    public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_POSITION && resultCode == Activity.RESULT_OK) {
            LatLng point = data.getExtras().getParcelable(PositionChooseActivity.EXTRA_POINT);
            Long bikeNumber = bikeManager.getCurrentBikeNumber();
            if (point != null && bikeNumber != null) {
                lockBike(point, bikeNumber);
            }
            return true;
        }
        return false;
    }

    private Bitmap createQRBitmap(String content) {
        Bitmap bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            result = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE,
                    UIUtils.dip2px(mContext, 240), UIUtils.dip2px(mContext, 240));
            // 使用 ZXing Android Embedded 要写的代码
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitmap = barcodeEncoder.createBitmap(result);
        } catch (WriterException e){
            e.printStackTrace();
        } catch (IllegalArgumentException iae){ // ?
            return null;
        }
        return bitmap;
    }

    public void showQrDialog() {
        Long currentbikeNumber = bikeManager.getCurrentBikeNumber();
        ImageView imageView = new ImageView(mContext);
        Bitmap bitmap = createQRBitmap(currentbikeNumber.toString());
        imageView.setImageBitmap(bitmap);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(UIUtils.dip2px(mContext, 240),
                UIUtils.dip2px(mContext, 240)));
        Dialog dialog = new AlertDialog.Builder(mContext)
                .setTitle(R.string.qr_code)
                .setPositiveButton(android.R.string.ok, null)
                .create();
        dialog.setCancelable(true);
        getUiControlInterface().showAlert(dialog);
        dialog.setContentView(imageView);
    }

    @Override
    public void start(Intent intent) {
        Long currentNumber = bikeManager.getCurrentBikeNumber();
        if (BikeManager.isRightBikeNumber(currentNumber)) {
            mActivity.setCurrentBikeNumber(currentNumber.toString());
            mActivity.setShowQrButtonEnabled(true);
            Message message = createLoadBikeMessage(currentNumber);
            message.sendToTarget();
        }
    }

    @Override
    public void stop() {
        mHandler.removeMessages(MSG_LOAD_BIKE_STATE);
    }

    private Message createLoadBikeMessage(Long bikeNumber) {
        Message message = mHandler.obtainMessage(MSG_LOAD_BIKE_STATE);
        message.obj = bikeNumber;
        return message;
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_BIKE_STATE:
                    loadBikeState((Long) msg.obj);
                    Message message = createLoadBikeMessage((Long) msg.obj);
                    mHandler.sendMessageDelayed(message, MSG_LOAD_BIKE_DELAY);
                    break;
                case MSG_DISMISS_PREGRESS_DIALOG:
                    getUiControlInterface().dismissProgress();
                    break;
                default:
                    break;
            }
        }
    };

    public void lockBike(LatLng point, Long bikeNumber) {
        getUiControlInterface().showProgress(mActivity.getString(R.string.locking));
        BikeLockTo bikeLockTo = new BikeLockTo(bikeNumber,
                new Double[] {point.longitude, point.latitude});
        bikeManager.lockBike(bikeLockTo, new DataListener() {
            @Override
            public void onSuccess(Object data, String message) {
                mHandler.sendEmptyMessageDelayed(MSG_DISMISS_PREGRESS_DIALOG, MSG_LOAD_BIKE_DELAY
                        + 1 * 1000);
                getUiControlInterface().showToast(message);
            }

            @Override
            public void onFailed(Throwable error, String message) {
                getUiControlInterface().showToast(message);
            }
        });
    }

    public void loadBikeState(Long bikeNumber) {
        bikeManager.queryBikeState(bikeNumber, new DataListener<Integer>() {
            @Override
            public void onSuccess(Integer data, String message) {
                //空闲中
                MainActivity.BikeState bikeState = MainActivity.BikeState.FREE;
                if (data == 1) {
                    bikeState = MainActivity.BikeState.FREE;
                    mActivity.setLockBtnEnabled(false);
                } else if (data == 2) {
                    bikeState = MainActivity.BikeState.IN_USE;
                    mActivity.setLockBtnEnabled(true);
                }
                mActivity.setTextBikeState(bikeState);
            }

            @Override
            public void onFailed(Throwable error, String message) {
                getUiControlInterface().showToast(message);
            }
        });
    }
}
